package com.kpmg.datalake.common.handler;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kpmg.datalake.common.exception.CustomException;
import com.kpmg.datalake.common.model.QueryRequestParam;

/**
 * 查询请求队列
 * @author tony
 */
public class QueryRequestQueue extends LinkedBlockingQueue<QueryRequestParam> {

	private static final Logger logger = LoggerFactory.getLogger(QueryRequestQueue.class);

	private static final long serialVersionUID = 8910201558861079910L;
	private static QueryRequestQueue queue = new QueryRequestQueue();
	private boolean flag = false;
	private static ThreadPoolExecutor service = new ThreadPoolExecutor(3, 4, 200, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
	private QueryRequestQueue() {
	}

	public static QueryRequestQueue getInstance() {
		return queue;
	}

	public void start() {
		if (!this.flag) {
			this.flag = true;
		} else {
			throw new CustomException("查询请求队列已启动，请勿重复启动。");
		}
		
		new Thread(()->{
			while (flag) {
				try {
					QueryRequestParam param = take();
					service.execute(new QueryRequestHandler(param));
					logger.info("请求接受:{}", param.getRequestNo());
				} catch (Exception e) {
					logger.info(e.getMessage());
				}
			}
		}).start();
	}

	public void stop() {
		this.flag = false;
	}

}
